package org.me.nyx.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import org.me.nyx.R;
import org.me.nyx.adapters.MovieAdapter;
import org.me.nyx.data.DataAdapter;
import org.me.nyx.domain.Movie;
import org.me.nyx.web.MovieLoader;

public class Movies extends Activity {
    private ListView moviesView;
    private DataAdapter<Movie> moviesAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.movies);

        moviesView = (ListView) findViewById(R.id.movies);
        moviesAdapter = new MovieAdapter(this, R.layout.movie_row);
        
        moviesView.setAdapter(moviesAdapter);
        moviesView.setOnItemClickListener(
			new OnItemClickListener() {
				public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
					onMovieSelected(adapter, view, position, id);
				}
			}
        );
		updateData();
    }

	public void reloadMovies(View view) {
		updateData();
	}

    @Override
    public void onDestroy() {
    	moviesAdapter.dispose();
    	super.onDestroy();
    }

    public void updateData() {
		Thread thread = new Thread(new MovieLoader(moviesAdapter));
		thread.start();
    }
    
    public void onMovieSelected(AdapterView<?> adapter, View view, int position, long id)
    {
    	Movie movie = (Movie)moviesView.getAdapter().getItem(position);
    	Intent intent = new Intent(view.getContext(), ViewMovie.class);
    	intent.putExtra("movie", movie.getId());
		startActivity(intent);
    }

    @Override
    public void onWindowFocusChanged(boolean focus ){
	if(focus)
	    updateData();
    }
}